package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.TimeSlotRemainingCountDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 预约信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-02
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation) {
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 统计今天取消的预约数量
     *
     * @return 今天取消的预约数量
     */
    @Override
    public int countTodayCancelledReservations() {
        // 获取当前时间戳
        long time = System.currentTimeMillis();
        // 将时间戳转换为LocalDateTime对象
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        // 计算今天的开始时间
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        // 计算今天的结束时间
        LocalDateTime endTime = startTime.plusDays(1);
        // 查询今天取消的预约数量
        return reservationMapper.countTodayCancelledReservations(startTime, endTime);
    }

    /**
     * 获取指定时间段内的时间段剩余数量
     *
     * @param time 时间戳
     * @return 时间段剩余数量列表
     */
    @Override
    public List<TimeSlotRemainingCountDto> getTimeSlotRemainingCounts(Long time) {
        // 将时间戳转换为LocalDateTime
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);

        // 获取当天的开始时间和结束时间
        LocalDateTime startOfDay = localDateTime.toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);

        // 查询每个时间段的剩余预约次数
        List<TimeSlotRemainingCountDto> result = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            LocalDateTime startTime = startOfDay.plusHours(i);
            LocalDateTime endTime = startTime.plusHours(1);

            // 查询该时间段内的预约数量
            /*int count = count(new LambdaQueryWrapper<Reservation>()
                    .ge(Reservation::getStartTime, startTime)
                    .lt(Reservation::getStartTime, endTime));*/
            // 使用实体类中实际的 time 字段对应的方法 getTime()
            long count = count(new LambdaQueryWrapper<Reservation>()
                    .ge(Reservation::getTime, startTime)
                    .lt(Reservation::getTime, endTime));

            // 只有剩余次数小于6的时间段才会返回（表示已被预约过）
            // 剩余6次的时间段不会出现在返回结果中
            if (count < 6) {
                TimeSlotRemainingCountDto timeSlotCount = new TimeSlotRemainingCountDto();
                timeSlotCount.setTime(startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                timeSlotCount.setCount((int) count);
                result.add(timeSlotCount);
            }
        }

        return result;
    }

    /**
     * 添加预约信息
     */
    @Override
    public void addReservation(Reservation  reservation) {
        // 自动填充创建时间（继承自BaseEntity）
        reservation.setCreateTime(new Date());
        // 设置初始状态为"待报道"（0）
        reservation.setStatus(0);
        reservationMapper.insertReservation(reservation);
    }

    @Override
    public void cancelReservation(Long id) {
        // 根据ID查询预约信息
        Reservation reservation = getById(id);
        if (reservation == null) {
            throw new RuntimeException("预约不存在");
        }

        // 更新预约状态为已取消（假设状态码为 -1 表示已取消）
        reservation.setStatus(-1);
        updateById(reservation);
    }
}
